import { apiClient } from './axios'

// 物料分类接口
export interface MaterialCategory {
  id: number
  name: string
  code: string
  parent_id?: number
  level: number
  sort_order: number
  description?: string
  is_active: boolean
  created_at: string
  updated_at: string
  children?: MaterialCategory[]
  parent?: MaterialCategory
  material_count?: number
}

export const materialCategoriesApi = {
  // 获取所有物料分类
  getMaterialCategories: () => {
    return apiClient.get<MaterialCategory[]>('/material-categories')
  },

  // 获取物料分类树形结构
  getMaterialCategoryTree: () => {
    return apiClient.get<MaterialCategory[]>('/material-categories/tree')
  },

  // 获取物料分类详情
  getMaterialCategory: (id: number) => {
    return apiClient.get<MaterialCategory>(`/material-categories/${id}`)
  },

  // 创建物料分类
  createMaterialCategory: (data: Omit<MaterialCategory, 'id' | 'created_at' | 'updated_at' | 'children' | 'parent' | 'material_count'>) => {
    return apiClient.post<MaterialCategory>('/material-categories', data)
  },

  // 更新物料分类
  updateMaterialCategory: (id: number, data: Partial<MaterialCategory>) => {
    return apiClient.put<MaterialCategory>(`/material-categories/${id}`, data)
  },

  // 删除物料分类
  deleteMaterialCategory: (id: number) => {
    return apiClient.delete(`/material-categories/${id}`)
  },

  // 获取子分类
  getChildCategories: (parentId: number) => {
    return apiClient.get<MaterialCategory[]>(`/material-categories/${parentId}/children`)
  },

  // 移动分类（更改父级）
  moveMaterialCategory: (id: number, newParentId: number | null) => {
    return apiClient.put(`/material-categories/${id}/move`, { parent_id: newParentId })
  },

  // 批量更新分类排序
  updateCategoriesOrder: (categories: Array<{ id: number; sort_order: number }>) => {
    return apiClient.put('/material-categories/batch-order', { categories })
  },

  // 获取分类路径（面包屑）
  getCategoryPath: (id: number) => {
    return apiClient.get<MaterialCategory[]>(`/material-categories/${id}/path`)
  },

  // 检查分类代码是否唯一
  checkCategoryCode: (code: string, excludeId?: number) => {
    const params = excludeId ? { exclude_id: excludeId } : {}
    return apiClient.get<{ isUnique: boolean }>(`/material-categories/check-code/${code}`, { params })
  },

  // 获取分类统计信息
  getCategoryStats: () => {
    return apiClient.get<{
      total_categories: number
      active_categories: number
      max_level: number
      categories_with_materials: number
    }>('/material-categories/stats')
  }
};